package org.room402.chat.process;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.reactivestreams.Publisher;
import org.room402.constant.chat.MessageAction;
import org.room402.entity.chat.ChatPool;
import org.room402.entity.chat.MessageEvent;
import org.room402.framework.chat.container.ChatPoolContainer;
import org.room402.framework.chat.container.UserSessionContext;
import org.room402.utile.chat.FastChatUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class PoolMsgEventProcess implements MessageProcess {
    private final UserSessionContext userSessionContext;
    private final ChatPoolContainer chatPoolContainer;

    @Override
    public boolean actionMatch(MessageEvent event, WebSocketSession session) {
        return MessageAction.send_msg.equals(event.getAction());
    }

    @Override
    public boolean rejectMatch(MessageEvent event, WebSocketSession session) {
        return !chatPoolContainer.isInPool(event.getTargetId(), userSessionContext.getBySid(session.getId()));
    }

    @Override
    public Publisher<Void> process(MessageEvent event, WebSocketSession session) {
        ChatPool pool = chatPoolContainer.get(event.getTargetId());

        return Flux.fromIterable(pool.getMembers())
                .map(userInfoView -> userSessionContext.getByUid(userInfoView.getId()))
                .flatMap(targetUser -> {
                    WebSocketSession targetSession = targetUser.getSession();
                    MessageEvent messageEvent = MessageEvent.form(event.getTargetId(), targetUser.getId(), MessageAction.pool_msg,
                            event.getOriginId() + ":" + event.getContent());
                    return targetSession.send(Mono.just(targetSession.textMessage(JSONUtil.toJsonStr(messageEvent))));
                });
    }

    @Override
    public Publisher<Void> reject(MessageEvent event, WebSocketSession session) {
        return FastChatUtil.reject(userSessionContext.getBySid(session.getId()), "您不属于该聊天池");
    }
}
